import API from '../api';
import {md5, isNode, fetch} from '../util';


let api
export default class SSO{
	constructor(options){
		api = new API(options)
	}
	syncFetch(...args){
		return api.genCommonMod('sync')(...args)
	}
	doRequest(url){
		if(isNode){
			fetch(url)
		} else {
			const elmId = `elmid_${Math.random()}`
			const script = document.createElement("script")
			script.src = url;
			script.id = elmId;
			document.head.appendChild(script);
			setTimeout(() => {
				const elem = script;
				const parent = elem.parentNode;
		        if(parent && parent.nodeType !== 11) {
		            parent.removeChild(elem);
		        }
			}, 200)
		}
	}
	requestSync(urls){
		if(Array.isArray(urls) && urls.length) {
			urls.forEach(i => this.doRequest(i))
		} else {
			this.doRequest(i)
		}
	}
	sync = async user => {
		const param = {
			act: 'login',
			user_id: user.user_id,
			user_access_token: md5(user.user_access_token),
		}
		const res = await this.syncFetch(param)
		if(res.urlRows && res.urlRows.length){
			this.requestSync(res.urlRows);
		}
		return res
	}
}